import React from 'react';
import FieldList from './fieldList';
import CommonListsIndex from '../../../components/CommonLists/index';
import FilterTool from '../../../components/FilterTool';
import services from '../../../services/api';
import { message } from 'antd';

class FieldIndex extends CommonListsIndex {
  constructor(props) {
    super(props);
    this.api = 'field';
    this.listsComponent = FieldList;
    this.queryParams = {};
    this.initQueryPanigation = {
      current_page: 1,
      page_size: 10,
    };
    this.state = {
      field_ids: [], // 已勾选的字段，复制要用
      applications: [],
      events: [],
      selectedRowKeys: [],
      app_id: '',
      event_id: '',
      filterItems: [],
    };
    this.isAppRequest = false;
    this.queryPanigation = {
      current_page: 1,
      page_size: 10,
    };

    this.queryTableParams = {};

    this.model_width = 600;
  }

  componentWillMount() {}

  componentDidMount() {
    this.getAppCodeList();
  }

  updateFilterItems = () => {
    this.setState({
      filterItems: [
        {
          type: 'Select',
          key: 'app_id',
          name: 'app_id',
          label: '应用',
          defaultValue: '',
          span: 8,
          options: [
            ...this.state.applications.map((item) => {
              return {
                value: item.app_id,
                name: item.app_name,
              };
            }),
          ],
          onChange: this.onAppChangeSelect,
        },
        {
          type: 'Select',
          key: 'event_id',
          name: 'event_id',
          label: '事件',
          defaultValue: '',
          span: 8,
          options: [
            ...this.state.events.map((item) => {
              return {
                value: item.event_id,
                name: item.event_name,
              };
            }),
          ],
          onChange: this.onEventChangeSelect,
        },
        {
          type: 'Search',
          key: 'name',
          name: 'name',
          defaultValue: '',
          span: 8,
          placeholder: '请输入字段名|字段Code进行搜索',
        },
      ],
    });
  };

  getAppCodeList = () => {
    services.application.getAppCodeList().then((res) => {
      if (res.code === 0) {
        res.data.shift();
        this.setState({
          applications: res.data,
        });
        this.updateFilterItems();
      }
    });
  };

  getEventCodeList = (app_id) => {
    services.event.getEventCodeList({ app_id: app_id || '' }).then((res) => {
      if (res.code === 0) {
        res.data.shift();
        this.setState({
          events: res.data,
        });
        this.updateFilterItems();
        this.refs.filterTool.handleChange('event_id', '');
      }
    });
  };

  freshQueryList = () => {
    if (this.isAppRequest) {
      this.isAppRequest = false;
    } else {
      if (this.queryParams.app_id && this.queryParams.event_id) {
        this.queryList({ ...this.queryParams, ...this.queryTableParams, ...this.queryPanigation });
      } else {
        this.clearList();
      }
    }
  };

  // 列表
  queryList = (params) => {
    services[this.api].list(params).then((res) => {
      if (res.code === 0) {
        this.setState({
          ...res.data,
        });
        this.props.updateAppAndEvent(this.state.app_id, this.state.event_id);
      } else {
        message.error(res.msg);
      }
    });
  };

  refreshPanagaition = (params) => {
    this.queryPanigation = {
      ...this.queryPanigation,
      ...params,
    };
  };
  refreshFilter = (params, type) => {
    this.queryParams = params;
    if (type === false) return
    this.freshQueryList();
  };

  refreshTableFilter = (params) => {
    this.queryTableParams = { ...this.queryTableParams, ...params };
    this.refreshPanagaition(this.initQueryPanigation);
    this.freshQueryList();
  };

  // onAppChangeSelect
  onAppChangeSelect = (name, e) => {
    this.isAppRequest = true;
    this.setState({
      event_id: '',
      app_id: e,
      selectedRowKeys: this.state.selectedRowKeys.splice(0),
    });
    this.getEventCodeList(e);
    this.props.updateAppAndEvent(e, this.state.event_id, true);
  };
  // onEventChangeSelect
  onEventChangeSelect = (name, e) => {
    this.setState({
      event_id: e,
      selectedRowKeys: this.state.selectedRowKeys.splice(0),
    });
    this.props.updateAppAndEvent(this.state.app_id, e, true);
  };

  updateSelectedRowKeys(field_id) {
    if (field_id) {
      this.state.selectedRowKeys[0] = field_id;
    } else {
      this.state.selectedRowKeys.splice(0);
    }
    this.setState({
      selectedRowKeys: this.state.selectedRowKeys,
    });
  }

  render() {
    const ListsComponent = this.listsComponent;
    // 字段选择配置
    const rowSelection = {
      columnWidth: 30,
      onChange: (selectedRowKeys, selectedRows) => {
        if (selectedRowKeys.length > 0) {
          selectedRowKeys.splice(0, selectedRowKeys.length - 1);
        }
        if (selectedRows.length > 0) {
          selectedRows = selectedRows.filter((item) => {
            return item.field_id === selectedRowKeys[0];
          });
        }
        this.props.updateMap(selectedRows, this.state.app_id, this.state.event_id);
        this.setState({
          selectedRowKeys,
        });
      },
      getCheckboxProps: (record) => {
        const mapping_relation_arr =
          (this.props.mapping_relation &&
            this.props.activeRow &&
            this.props.mapping_relation[this.state.app_id] &&
            this.props.mapping_relation[this.state.app_id][this.state.event_id] &&
            Object.values(this.props.mapping_relation[this.state.app_id][this.state.event_id])) ||
          [];
        const active_id = this.props.activeRow ? this.props.activeRow.param_id : undefined;
        const current =
          (this.props.mapping_relation &&
            this.props.mapping_relation[this.state.app_id] &&
            this.props.mapping_relation[this.state.app_id][this.state.event_id] &&
            active_id &&
            this.props.mapping_relation[this.state.app_id][this.state.event_id][active_id]) ||
          undefined;
        const isCurrent = (current && current.field_code === record.field_code) || false;

        return {
          disabled:
            this.props.disabled ||
            !!(mapping_relation_arr.length > 0
              ? mapping_relation_arr.filter((it) => !!it).find((it) => it.field_code === record.field_code)
                ? isCurrent
                  ? false
                  : true
                : false
              : false),
          name: record.field_id,
        };
      },
      hideDefaultSelections: true,
      selectedRowKeys: this.state.selectedRowKeys,
    };
    return (
      <div>
        <FilterTool
          ref='filterTool'
          data={this.state.filterItems}
          colNum={3}
          query={this.freshQueryList}
          refreshFilter={this.refreshFilter}
          isOnChange={true}
          isNotShowExpened={true}
          isSearchNotSpaceBetween={true}
        />
        <div style={{ marginTop: '10px' }} className='field-map-table'>
          <ListsComponent
            {...this.state}
            rowKey='field_id'
            applications={this.state.applications}
            edit={this.edit}
            queryList={this.freshQueryList}
            refreshTableFilter={this.refreshTableFilter}
            onChangePagination={this.onChangePagination}
            showDetail={this.showDetail}
            rowSelection={rowSelection}
            queryTableParams={this.queryTableParams}
            paginationSize={'small'}
          />
        </div>
      </div>
    );
  }
}

export default FieldIndex;
